package com.agou.ssh.web.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.agou.app.AppContext;
import com.agou.core.ss.SSTrace;
import com.agou.ssh.web.WebUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthorizationInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = -6721240719300618409L;
	private static SSTrace ssTrace = SSTrace.getInstance(AuthorizationInterceptor.class);
	private ServletContext servletContext;
	private static List<String> excludeActions = new ArrayList<String>();
	
	public static final String ACTION_LOGIN = "global.login";
	
	 public void init(){
		 String actions = servletContext.getInitParameter("AuthorizationInterceptor.excludeActions");
		 WebUtil.setProjectName(servletContext.getInitParameter("global.projectName"));
		 WebUtil.setServiceName(servletContext.getInitParameter("global.serviceName"));
		 //ssTrace.debug("init", "初始化验证拦截器:#0", actions);
		 if(actions != null && actions.length() > 0){
			 String[] tempActions = actions.split(",");
			 for(int i = 0 ; i < tempActions.length ; i++){
				 excludeActions.add(tempActions[i]);
			 }
		 }
	 };

	public String intercept(ActionInvocation ai) throws Exception {
		HttpServletRequest request =ServletActionContext.getRequest();
		Map<String,Object> session = ai.getInvocationContext().getSession();
		AppContext acx = (AppContext)session.get(AppContext.APP_NAME);
		if(acx == null){
			String loginAuth = ai.getInvocationContext().getName();
			if(excludeActions.contains(loginAuth)){
				ssTrace.debug("intercept", "#0 免登陆：#1",loginAuth, request.getRequestURI());
				return ai.invoke();
			}else{
				ssTrace.debug("intercept", "用户未认证:#0", request.getRequestURI());
				return ACTION_LOGIN;//进入登陆页面
			}
		}else{
			//acx.requestURI = request.getRequestURI();
			acx.servletPath = request.getServletPath();
			acx.sysTimestamp = System.currentTimeMillis();//每一次请求产生一个时间戳
			session.put(AppContext.APP_NAME, acx);
			return ai.invoke();
		}
	}
	
	
	public void setServletContext(ServletContext context) {  
	    this.servletContext = context;  
	}  
}